package cn.uyunsky.platform.config.loader;

import cn.uyunsky.platform.config.ConfigBeanInterface;
import cn.uyunsky.platform.config.ConfigLoader;
import cn.uyunsky.platform.config.bean.page.PageBean;
import cn.uyunsky.platform.config.bean.page.PageDefineBean;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;

import java.util.List;

public class PageDefineLoader implements ConfigLoader {
    private static final String PAGE = "page";

    @Override
    public ConfigBeanInterface loadConfig(Resource resource, Class<? extends ConfigBeanInterface> clazz) throws Exception {
        PageDefineBean config = new PageDefineBean();

        String pageFilename = resource.getFilename();
        String subfix = "";
        if (pageFilename.indexOf(".") != pageFilename.lastIndexOf(".")) {
            subfix = pageFilename.substring(pageFilename.indexOf(".") + 1, pageFilename.lastIndexOf("."));
        }

        SAXReader reader = new SAXReader();
        Document doc = reader.read(resource.getInputStream());
        Element root = doc.getRootElement();

        List<?> pageList = root.elements(PAGE);
        for (int j = 0; j < pageList.size(); j++) {
            Element page = (Element) pageList.get(j);
            String pagecode = page.attributeValue("pagecode");
            PageBean bean = new PageBean();
            bean.setPagecode(pagecode);
            bean.setUri(page.attributeValue("uri"));
            bean.setService(page.attributeValue("service"));
            bean.setDesc(page.getTextTrim());
            bean.setName(page.attributeValue("name"));
            bean.setLevel(subfix);

            if (config.containsKey(pagecode)) {
                throw new Exception("页面码[" + pagecode + "]已存在");
            }
            config.put(pagecode, bean);
        }
        return config;
    }
}
